<?php
use Lib\ResLoader;
use Doctrine\Common\Util\Debug;
class Zend_View_Helper_PartialCache extends Zend_View_Helper_Abstract{
    /**
     * @var \Zend_Cache_Corepartials
     */
    protected $_cache = false;
    public function partialCache($name = null, $module = null, $model = null, $cacheData = null){
        if(null === $cacheData){
            return $this->view->partial($name, $module, $model);
        } else {
            if(!$cache = $this->getCache()){
                $cache = ResLoader::getCache();
                $this->setCache($cache);
            }
                // Generate id for cache
                $id = serialize($name);

                if(is_object($module)){
                    $id .= Debug::toString($module);
                } else {
                    $id .= serialize($module);
                }

                if(is_object($model)){
                    $id .= Debug::toString($model);
                } else {
                    $id .= serialize($model);
                }
                // generated id
                $id = 'partial_'.md5($id);
                // retrieve result from cache
                if(!$result = $this->_cache->load($id)){
                    $result = $this->view->partial($name, $module, $model);
                    // saving result
                    if(is_array($cacheData)){
                        // cache priority
                        $priority = (isset($cacheData['priority']) && $cacheData['priority'] != null )?$cacheData['priority']:8;
                        // cache lifetime
                        $lifetime = (isset($cacheData['lifetime']) && $cacheData['lifetime'] !== null )?$cacheData['lifetime']:false;
                        // cache tags
                        $tags     = (isset($cacheData['tags']) && $cacheData['tags'] !== null )?(is_array($cacheData['tags'])?$cacheData['tags']:array()):array();
                    } else {
                        $priority = 8;
                        $lifetime = false;
                        $tags = array();
                    }
                    $this->_cache->save($result, $id, $tags, $lifetime, $priority);
                }
                return $result;

        }
    }

    public function setCache($cache) {
        $this->_cache = $cache;
    }

    public function getCache() {
        return $this->_cache;
    }
}